//
//  AppDelegate.m
//  iPhone Backup Slurp
//
//  Created by Bob Newhart on 10/15/08.
//  Copyright 2008 Geekspiff. All rights reserved.
//

#import "AppDelegate.h"
#import "ManifestDocument.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(windowDidBecomeMain:) name: NSWindowDidBecomeMainNotification object: nil];
}

- (NSArray *)_visibleWindowsIgnoringWindow: (NSWindow *)ignoreWindow
{
	NSArray *allWindows = [NSApp windows];
	NSMutableArray *visibleWindows = [NSMutableArray arrayWithArray: allWindows];
	for (NSWindow *window in allWindows) {
		if (window == ignoreWindow || window == helpWindow || ![window isVisible])
			[visibleWindows removeObject: window];
	}
	
	return visibleWindows;
}

- (void)windowDidBecomeMain: (NSNotification *)notification
{
	if (0 != [[self _visibleWindowsIgnoringWindow: nil] count])
		[helpWindow orderOut: nil];
}

- (IBAction)openManifest: (id)sender
{
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setCanChooseFiles: YES];
	[openPanel setCanChooseDirectories: NO];
	[openPanel setAllowsMultipleSelection: YES];
	[openPanel setDelegate: self];
	
	[_currentOpenPanelFilename release];
	_currentOpenPanelFilename = [@"Manifest.plist" retain];
	
	[openPanel beginSheetForDirectory: [NSHomeDirectory() stringByAppendingPathComponent: @"Library/Application Support/MobileSync/Backup"] 
								 file: nil
								types: [NSArray arrayWithObject: @"plist"]
					   modalForWindow: nil
						modalDelegate: self
					   didEndSelector: @selector(openManifestDidEnd:returnCode:contextInfo:)
						  contextInfo: NULL];
}

- (void)openManifestDidEnd: (NSOpenPanel *)openPanel returnCode: (NSInteger)returnCode contextInfo: (void *)contextInfo
{
	if (NSOKButton != returnCode) return;
	
	NSDocumentController *dc = [NSDocumentController sharedDocumentController];
	for (NSString *path in [openPanel filenames]) {
		NSError *error;
		ManifestDocument *document = [dc openDocumentWithContentsOfURL: [NSURL fileURLWithPath: path] display: YES error: &error];
		if (!document) {
			[NSApp presentError: error];
			return;
		}
	}
}

- (BOOL)panel:(NSOpenPanel *)sender shouldShowFilename:(NSString *)filename
{
	NSFileManager *fm = [NSFileManager defaultManager];
	BOOL exists, isDirectory;
	exists = [fm fileExistsAtPath: filename isDirectory: &isDirectory];
	if (isDirectory) return YES;
	return [[filename lastPathComponent] isEqualToString: _currentOpenPanelFilename];
}

@end
